<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="外联单位" size="small">
            <el-input v-model="searchForm.companyTitle"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="项目名称" size="small">
            <el-input v-model="searchForm.projectName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="440px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">

          <el-form-item prop="companyTitle" label="外联单位" size="small">
            <el-autocomplete
              v-model="teamRow.companyTitle"
              :fetch-suggestions="querySearchOutitemsCompany"
              @select="handleSelectOutitemsCompany"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="projectName" label="所属项目" size="small">
            <el-autocomplete
              v-model="teamRow.projectName"
              :fetch-suggestions="querySearchProject"
              @select="handleSelectProject"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item prop="receiveCompany" label="收款单位" size="small">
            <el-input type="text" v-model="teamRow.receiveCompany"></el-input>
          </el-form-item>
          <el-form-item prop="billDate" label="收款日期" size="small">
            <el-date-picker
              v-model="teamRow.billDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="billAmount" label="收款金额" size="small">
            <el-input type="text" v-model.number="teamRow.billAmount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="billCode" label="收款编号" size="small">
            <el-input type="text" v-model="teamRow.billCode"></el-input>
          </el-form-item>
          <el-form-item prop="operator" label="经办人" size="small">
            <el-autocomplete
              v-model="teamRow.operator"
              :fetch-suggestions="querySearchOperator"
              placeholder="请输入内容"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false;isAddress = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.billId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; schedule: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    deleteOutbill,
    getOutbillList,
    insertOutbill,
    selectCompany,
    selectOperator,
    selectOutbill,
    selectProject,
    updateOutbill
  } from '@/api/outbill'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const billTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :min-width="colConfig.minWidth">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'companyTitle', label: '外联单位名称', minWidth: '15%', fixed: true },
          { prop: 'projectName', label: '所属项目', minWidth: '15%' },
          { prop: 'billCode', label: '收款编号', minWidth: '15%' },
          { prop: 'receiveCompany', label: '收款单位', minWidth: '20%' },
          { prop: 'billTime', label: '收款日期', minWidth: '15%', component: billTime },
          { prop: 'billAmount', label: '收款金额(万元)', minWidth: '15%' },
          { prop: 'operator', label: '经办人', minWidth: '15%' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        scheduleLoading: true,
        dialogTitle: '新增外联项目到账表',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        isAddress: true, // 地区新增 修改 摧毁 生成组件
        pca: pca,
        rules: {
          projectName: [
            { required: true, message: '请输入项目名称', trigger: 'change' }
          ],
          companyTitle: [
            { required: true, message: '请输入外联单位', trigger: 'change' }
          ],
          receiveCompany: [
            { required: true, message: '请输入收款单位', trigger: 'change' }
          ],
          billDate: [
            { required: true, message: '请选择收款日期', trigger: 'change' }
          ],
          billAmount: [
            { required: true, message: '请输入收款金额', trigger: 'change' },
            { type: 'number', message: '请输入数字', trigger: 'change' }
          ],
          billCode: [
            { required: true, message: '请输入收款编号', trigger: 'change' }
          ],
          operator: [
            { required: true, message: '请输入经办人', trigger: 'change' }
          ]
        },
        visible: false
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getOutbillList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          console.log(this.tableData)
          this.listLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.outerVisible = true
        this.isAddress = true
        this.dialogTitle = '新增外联项目到账表'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.dialogType = 1
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
      },
      editTeam(billId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.isAddress = true
        this.dialogTitle = '修改外联项目到账表'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          billId: billId
        }
        selectOutbill(params).then(response => {
          this.teamRow = response.responseBody
          this.$set(this.teamRow, 'billDate', formatDate(new Date(this.teamRow.billTime), 'yyyy-MM-dd'))
        })
      },
      submitForm(formName) {
        const params = JSON.parse(JSON.stringify(this.teamRow))
        console.log(params)
        delete params.addressId
        delete params.address
        if (this.teamRow.outProjectId && delete this.teamRow.outCompanyId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                insertOutbill(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.isAddress = false
                  this.fetchData()
                })
              } else {
                updateOutbill(params).then(response => {
                  console.log(response)
                  this.outerVisible = false
                  this.isAddress = false
                  this.fetchData()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else if (!this.teamRow.outCompanyId) {
          this.$message({
            message: '该外联单位不存在',
            type: 'warning'
          })
        } else if (!this.teamRow.outProjectId) {
          this.$message({
            message: '该项目不存在',
            type: 'warning'
          })
        }
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          billId: scope.row.billId,
          isDel: 1
        }
        deleteOutbill(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      addressChange() {
        this.teamRow.provinceId = this.teamRow.addressId[0]
        this.teamRow.cityId = this.teamRow.addressId[1]
        this.teamRow.address = this.pca[86][this.teamRow.addressId[0]] + this.pca[this.teamRow.addressId[0]][this.teamRow.addressId[1]]
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.outProjectId
        if (queryString) {
          const params = {
            projectName: queryString
          }
          selectProject(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.projectName
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.teamRow.outProjectId = item.projectId
      },
      querySearchOutitemsCompany(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.outCompanyId
        if (queryString) {
          const params = {
            projectName: queryString
          }
          selectCompany(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.companyTitle
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectOutitemsCompany(item) {
        this.teamRow.outCompanyId = item.companyId
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            projectName: queryString
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      schedule-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        schedule: 0 20px;
      }
      .el-dialog {
        textarea {
          schedule-top: 10px;
        }
        .el-checkbox {
          schedule-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          schedule-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
